package cn.edu.scau.cmi.liujianxun.springhibernate.dao;

import java.util.List;

import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.edu.scau.cmi.liujianxun.springhibernate.dao.StudentDAO;
import cn.edu.scau.cmi.liujianxun.springhibernate.domain.Student;
import cn.edu.scau.cmi.liujianxun.springhibernate.util.HibernateSessionFactoryUtil;

public class StudentDAO {
	private static final Logger log = LoggerFactory.getLogger(StudentDAO.class);
	// property constants
	public static final String NAME = "name";
	//dao依赖hibernate session对象。使用spring封装该属性。
	private Session session;
	
	

	public void save(Student transientInstance) {
		try {
			getSession();
			Transaction transaction = session.beginTransaction();
			session.save(transientInstance);
			transaction.commit();
		} catch (RuntimeException re) {
			throw re;
		}
	}

	private Session getSession() {
		session = HibernateSessionFactoryUtil.getSession();
		return session;
	}

	public void delete(Student persistentInstance) {
		log.debug("deleting Student instance");
		try {
			getSession().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public Student findById(java.lang.Long id) {
		log.debug("getting Student instance with id: " + id);
		try {
			Student instance = (Student) getSession().get("cn.edu.scau.cmi.liujianxun.springhibernate.domain.Student", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public void update(Student s) {
		log.debug("update Student instance");
		try {
			getSession();
			Transaction transaction = session.beginTransaction();
			session.update(s);
			transaction.commit();
			log.debug("update successful");
		} catch (RuntimeException re) {
			log.error("update failed", re);
			throw re;
		}
	}
}
